<!-- 百人(Luck49) -->
<template>
  <el-dialog v-if="props.show" :model-value="props.show" :title="'【百人场】' + data.game_name" top="8vh" width="58%"
    @close="onHideDetails" :close-on-press-escape="false" :destroy-on-close="true" :close-on-click-modal="false">
    <div v-loading="indexStore.moduleLoading">
      <div class="dialogMaxHeight" :class="props.isDisableUser ? 'disableUser' : ''">
        <el-form ref="ruleFormRef" :model="data" :inline="true" :rules="rules" :scroll-to-error="true">
          <form-item title="游戏名称" value="game_name">
            <GameHeaderInfo :game_id="props.checkedItem.game_id" />
          </form-item>
          <form-item title="商户" :pass="true" value="agent_id" v-show="data.agent_id">
            <el-select v-model="data.agent_id" placeholder="请选择" filterable @change="chooseOperator">
              <el-option v-for="item in indexStore.agentArray" :key="item.value"
                :label="'【' + item.value + '】' + item.label" :value="item.value" />
            </el-select>
            <span class="tipsText"> (此游戏所属商户)</span>
          </form-item>
          <form-item title="游戏水位" :pass="true" value="pool" v-show="data.agent_id && !indexStore.is_general_agent">
            <div class="flexWarp">
              <span class="margin5" v-for="(item, index) in data.serverPoolList" :key="index">
                <el-tag type="danger">{{ item.label }}</el-tag>：
                <el-input-number v-model="item.value" :min="-99999999999999999999" :max="99999999999999999999"
                  :precision="0" placeholder="游戏水位" clearable controls-position="right" />
              </span>
            </div>
          </form-item>
          <form-item title="房间最大人数" :pass="true" value="a_hundred_num" v-show="!indexStore.is_general_agent">
            <el-input-number v-model="data.a_hundred_num" :min="0" :max="99999999999999999999" :precision="0"
              placeholder="房间最大人数" clearable controls-position="right" />
            <span class="tipsText"> (游戏房间能进入的玩家最大人数)</span>
          </form-item>
          <form-item title="利润率" :pass="true" value="a_hundred_profitmargin">
            <el-input-number v-model="data.a_hundred_other_details.a_hundred_profitmargin" :min="0" :max="3"
              :precision="0" placeholder="利润率" clearable controls-position="right" />%
            <span class="tipsText"> (玩家下注流水*利润率的值；建议值为3%)</span>
          </form-item>
          <form-item title="预下注期数" :pass="true" value="a_hundred_prebetting">
            <el-input-number v-model="data.a_hundred_other_details.a_hundred_prebetting" :min="0" :max="50"
              :precision="0" placeholder="利润率" clearable controls-position="right" />
            <span class="tipsText"> (玩家可以下注的最大未来期数差值,例如当前期50 这里配置10，那么玩家只能最多提前下注到60期)</span>
          </form-item>
          <form-item title="押注金额" :pass="true" value="a_hundred_stake">
            <div class="flex margin5" v-for="(item, index) in data.pressureList" :key="index">
              最小押注:
              <el-input-number :min="0" :max="99999999999999999999" :precision="4" class="marginR10" v-model="item.min"
                placeholder="请输入最小押注" clearable controls-position="right" />
              最大押注:
              <el-input-number :min="item.min" :max="99999999999999999999" :precision="4" class="" v-model="item.max"
                placeholder="请输入最大押注" clearable controls-position="right" />
            </div>
          </form-item>
          <form-item title="连续判定避重" :pass="true" value="a_hundred_repeat">
            <div class="flex margin5" v-for="(item, index) in data.repeatList" :key="index">
              判断重复局数:
              <el-input-number :min="0" :max="99999999999999999999" :precision="0" class="width150 marginR10"
                v-model="item.min" placeholder="请输入判断重复局数" clearable controls-position="right" />
              出现数字个数:
              <el-input-number :min="0" :max="item.min" :precision="0" class="width150" v-model="item.max"
                placeholder="请输入出现数字个数" clearable controls-position="right" />
            </div>
            <div class="tipsTextRed">(出现个数不能大于判断局数)</div>
          </form-item>
          <form-item title="返奖配置开关" :pass="true" value="rebate">
            <el-radio-group v-model="data.rebate" size="large">
              <el-radio-button label="关闭" :value="0" />
              <el-radio-button label="开启" :value="1" />
            </el-radio-group>
            <span class="tipsText"> (小火箭点击后弹出的返奖界面开关)</span>
          </form-item>
          <form-item title="返奖配置" value="a_hundred_rebate" :subtract="!props.isDisableUser" @addItem="addRebate">
            <div class="flexWrap margin5" v-for="(item, index) in data.rebateList" :key="index">
              返奖:
              <el-input-number v-model="item.max" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width150 marginR5" placeholder="玩家个人下注总额" clearable :controls="false" />
              玩家个人下注总额:
              <el-input-number v-model="item.min" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width200 marginR5" placeholder="返奖" clearable :controls="false" />
              <div v-show="!props.isDisableUser" class="reduce-btn marginL5" @click="reduceRebate(index)">-</div>
            </div>
            <span class="tipsText"> (小火箭点击后返奖界面的宝箱返奖配置,,<span class="tipsTextRed">最多只能配置8个档位</span>)</span>
          </form-item>
          <form-item title="单个赔率" :pass="true" value="a_hundred_odds" v-show="!indexStore.is_general_agent">
            <el-select v-model="data.a_hundred_other_details.a_hundred_odds" placeholder="请选择" filterable>
              <el-option label="10200" :value="10200" />
            </el-select>
          </form-item>
          <form-item title="初始水位" :pass="true" value="a_hundred_poolstart" v-show="!indexStore.is_general_agent">
            <el-input-number v-model="data.a_hundred_other_details.a_hundred_poolstart" :min="0" :max="100"
              :precision="0" class="width150" placeholder="初始水位" clearable :controls="false" />
          </form-item>
          <form-item title="水位配置" value="a_hundred_pool" :subtract="!props.isDisableUser" @addItem="addPool"
            v-show="!indexStore.is_general_agent">
            <div class="flexWrap margin5" v-for="(item, index) in data.poolList" :key="index">
              水位下限:
              <el-input-number v-model="item.min" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width120 marginR5" placeholder="水位下限" clearable :controls="false" />
              水位上限:
              <el-input-number v-model="item.max" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width120 marginR5" placeholder="水位上限" clearable :controls="false" />
              权重:
              <el-input-number v-model="item.weight" :min="-1" :max="99999999999999999999" :precision="0"
                class="width120 marginR5" placeholder="权重" clearable :controls="false" />
              输上限额度:
              <el-input-number v-model="item.lose" :min="-99999999999999999999" :max="99999999999999999999"
                :precision="4" class="width120 marginT5" placeholder="输上限额度" clearable :controls="false" />
              <div v-show="!props.isDisableUser" class="reduce-btn marginL5" @click="reducePool(index)">-</div>
            </div>
          </form-item>
        </el-form>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer" v-show="!props.isDisableUser">
        <el-button type="info" @click="onHideDetails">取 消</el-button>
        <el-button type="primary" @click="gameSet(ruleFormRef)" v-loading="indexStore.moduleLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { selectToLabel } from '@/utils/index'
import { BigWan, BigTimeWan } from '@/utils/math'
import { throttle } from '@/utils/index'
import { getHundredConfig, editHundredConfig, getPool, editPool } from '@/api/game'
import type { MinMax, RobotPoolBattleRoyale } from './gameType'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  isDisableUser: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  checkedItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const data = reactive({
  id: 0,
  game_id: 0,
  agent_id: 0,
  game_name: '',
  operated_id: indexStore.agentArray[0]?.value,
  a_hundred_num: 0, // 房间最大人数
  a_hundred_other_details: {
    a_hundred_profitmargin: 0, // 利润率
    a_hundred_stake: '', // 押注金额
    a_hundred_poolstart: 0, // 初始水位
    a_hundred_prebetting: 0, // 预下注期数
    a_hundred_odds: 0, // 单个赔率（赔率过高会导致模型崩溃）
    a_hundred_pool: '', // 水位配置
    a_hundred_repeat: '', // 连续判定避重(判定重复局数，出现数字个数)
    a_hundred_rebate: '', // 返奖(开关【1开，其余值关】;流水1，返奖额度1;流水2，返奖额度2;……)
  },
  pressureList: [{ min: 0, max: 0 }], // 押注金额
  repeatList: [{ min: 0, max: 0 }], // 连续判定避重
  poolList: [] as RobotPoolBattleRoyale[], // 水位配置
  rebate: 0, // 返奖(开关【1开，其余值关】)
  rebateList: [] as MinMax[], // 返奖配置
  serverPoolList: [] as any[], // 服务器水位配置
})

watch(
  () => [props.checkedItem, props.show],
  async (value) => {
    if (value[0]) {
      Object.assign(data, props.checkedItem)
    }
    if (value[1]) {
      chooseOperator(props.checkedItem.agent_id, props.checkedItem.game_id) // 获取运营商配置
    }
  }
)

// 选择运营商
const chooseOperator = async (id: number, game_id: number) => {
  indexStore.setModuleLoading(true)
  // 水位
  if (data.agent_id && !indexStore.is_general_agent) {
    data.serverPoolList = []
    let agent = await getPool({ agent_id: props.checkedItem.agent_id, game_id: props.checkedItem.game_id });
    let keyData = Object.keys(agent.data);
    keyData.forEach((key: string) => {
      data.serverPoolList.push({ label: selectToLabel(indexStore.serverNameList, key), value: BigWan(agent.data[key] ? agent.data[key] : 0), server: key })
    })
  }
  // 游戏详情
  let res = await getHundredConfig({ agent_id: id, game_id: game_id });
  Object.assign(data, res.data)
  nextTick(() => {
    indexStore.setModuleLoading(false)
  })
}

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<typeof data>>({
  a_hundred_num: [{ required: true, message: '请输入房间最大人数', trigger: 'blur' }],
})
const gameSet = throttle(async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await editHundredConfig(data);
      if (data.agent_id && !indexStore.is_general_agent) {
        // 按服务器修改水位
        let pools = [] as number[], server = [] as any[];
        data.serverPoolList.forEach((item: any) => {
          pools.push(BigTimeWan(item.value))
          server.push(item.server)
        })
        await editPool({
          agent_id: data.agent_id,
          game_id: data.game_id,
          pools: pools.join(','),
          server_ids: server.join(','),
        })
      }
      ElMessage.success('修改成功')
      emit('onHideDetails', true)
    }
  })
}, 5000)

// 重置
const emit = defineEmits(['onHideDetails'])
const onHideDetails = () => {
  emit('onHideDetails', false)
}

// 玩家返奖配置
const addRebate = () => {
  if (data.rebateList.length > 7) {
    return ElMessage.error('最多只能配置8个档位')
  }
  data.rebateList.push({ min: 0, max: 1 })
}
const reduceRebate = (index: number) => {
  data.rebateList.splice(index, 1)
}

// 水位配置
const addPool = () => {
  data.poolList.push({ min: 0, max: 1, weight: 0, lose: 0 })
}
const reducePool = (index: number) => {
  data.poolList.splice(index, 1)
}
</script>

<style scoped lang="scss"></style>